<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/2/28
 * Time: 23:03
 */

namespace app\admin\service;

use app\common\model\mysql\Admin;
use think\facade\Db;

class AdminService
{
    protected $adminModel = null;

    public function __construct()
    {
        $this->adminModel = new Admin();
    }

    /**
     * @param $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($data)
    {
        $adminUser = $this->getAdminByUsername($data['username']);
        if (!$adminUser) {
            throw new \think\Exception("不存在该用户");
        }

        // 判断密码是否正确
        if ($adminUser['password'] != md5(md5($data['password']).$adminUser['salt'])) {
            throw new \think\Exception("密码错误");
        }

        // 更新登录信息
        $updateData = [
            'last_login_time' => time(),
            'last_login_ip'   => request()->ip(),
        ];
        $res        = $this->adminModel->updateById($adminUser['id'], $updateData);
        if (empty($res)) {
            throw new \think\Exception("登录信息更新失败");
        }

        session("session_admin", $adminUser);

        return true;
    }

    /**
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminByUsername($username)
    {
        $admin = $this->adminModel->getAdminByUsername($username);
        if (empty($admin) || $admin['status'] != config('status.mysql.normal')) {
            return [];
        }

        return $admin;
    }

    /**
     * 根据id获取用户信息
     * @param $id
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminByUid($id)
    {
        $admin = $this->adminModel->getAdminByUid($id);
        if (empty($admin) || $admin['status'] != config('status.mysql.normal')) {
            return [];
        }

        return $admin;
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateProfileById($id, $data)
    {
        if (empty($data['password']) || $data['password'] == "") {
            unset($data['password']);
        }
        $profile = $this->adminModel->updateById($id, $data);
        if (false === $profile) {
            throw new \think\Exception("个人资料更新失败");
        }

        return true;
    }

    /**
     * @param $id
     * @param $path
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function saveAvatar($id, $path)
    {
        $data   = [
            'avatar' => $path,
        ];
        $avatar = $this->adminModel->updateById($id, $data);
        if (false === $avatar) {
            throw new \think\Exception("头像更新失败");
        }

        return true;
    }

    public function getAllAdmins()
    {
        $result = $this->adminModel->getAllAdmins();
        if (empty($result)) {
            throw new \think\Exception("获取所有管理员信息失败");
        }

        return $result;
    }

    public function deleteAdminAndAccessGroupById($id)
    {
        $result = $this->adminModel->deleteAdminAndAccessGroupById($id);
        if (false === $result) {
            throw new \think\Exception("管理员删除失败");
        }

        return true;
    }

    public function addAdmin($group_id, $data)
    {
        // todo :需要将添加后的id和group_id存入中间表

        // 密码数据加密
        $data['salt']     = getRandKey();
        $data['password'] = md5(md5($data['password']).$data['salt']);
        $result           = $this->adminModel->addAdmin($group_id, $data);
        if (false === $result) {
            throw new \think\Exception("管理员添加失败");
        }

        return true;
    }

    /**
     * @param $id
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOneAdminById($id)
    {
        // todo: 获取管理员信息也要获取group_id
        $group_id     = Db::name('auth_group_access')->where('uid', $id)->value('group_id');
        $dataForAdmin = $this->adminModel->getAdminByUid($id);
        if (empty($dataForAdmin)) {
            return [];
        }

        $dataForAdmin['group_id'] = $group_id;

        return $dataForAdmin;
    }

    public function updateAdminAndGroupById($id, $group_id, $data)
    {
        // todo: 不仅更新管理员表信息还要更新中间表的信息
        $result = $this->adminModel->updateAdminAndGroupById($id, $group_id, $data);
        if (false === $result) {
            throw new \think\Exception("管理员信息更新失败");
        }

        return true;
    }
}